package org.vectrics.mail;

import java.io.Writer;
import java.util.Map;
import org.apache.log4j.Logger;
import org.vectrics.SystemException;
import freemarker.core.Environment;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

public class TemplateMergeProcess implements TemplateExceptionHandler {
	public static String PARAM_NOT_FOUND_MESSAGE = "PARAM-NOT-FOUND";
	private Template freeMarkerTemplate = null;
	private RecipientTemplateMergeResult result = new RecipientTemplateMergeResult();
	private Logger log = Logger.getLogger(this.getClass());
	
	public TemplateMergeProcess(Template freeMarkerTemplate) {
		super();
		this.freeMarkerTemplate = freeMarkerTemplate;
	}
	
	public RecipientTemplateMergeResult process(Writer writer, Map<String, Object> parameters) {
		try {
			result.setResult(RecipientTemplateMergeResult.OK);
			this.freeMarkerTemplate.getConfiguration().setTemplateExceptionHandler(this);
			this.freeMarkerTemplate.process(parameters, writer);
		} catch (Exception ex) {
			throw new SystemException("Exception processing template", ex);
		}
		return(this.result);
	}
	
	public void handleTemplateException(TemplateException exception, Environment environment, Writer writer) throws TemplateException {
		log.warn("Error merging template", exception);
		result.setResult(RecipientTemplateMergeResult.ERROR);
		result.addMissingParameter(exception.getMessage());
		try {
            writer.write(PARAM_NOT_FOUND_MESSAGE);// + exception.getMessage() + "]");
        } catch (Exception e) {
            throw new TemplateException("Failed to print error message. Cause: " + e, environment);
        }
	}

	
}
